import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/Layout.vue'
import { useAuthStore } from '../stores/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/auth/Login.vue')
    },
    {
      path: '/',
      component: Layout,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Dashboard',
          component: () => import('../views/Dashboard.vue')
        },
        {
          path: 'resident',
          name: 'ResidentManagement',
          component: () => import('../views/resident/ResidentManagement.vue')
        },
        {
          path: 'staff',
          name: 'StaffManagement',
          component: () => import('../views/staff/StaffManagement.vue')
        },
        {
          path: 'medical',
          name: 'MedicalCare',
          component: () => import('../views/medical/MedicalCare.vue')
        },
        {
          path: 'activities',
          name: 'Activities',
          component: () => import('../views/activities/Activities.vue')
        },
        {
          path: 'dining',
          name: 'DiningManagement',
          component: () => import('../views/dining/DiningManagement.vue')
        },
        {
          path: 'facility',
          name: 'FacilityManagement',
          component: () => import('../views/facility/FacilityManagement.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!authStore.isAuthenticated) {
      next({ name: 'Login' })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router